import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from 'axios'
const Login = () => import('../components/Login.vue')
const Index = () => import('../components/Index.vue')
const Home = () => import('../components/Home.vue')

const Goods = () => import(/* webpackChunkName: 'goods' */'../components/Goods.vue')
const GoodsAdd = () => import(/* webpackChunkName: 'goods' */'../components/GoodsAdd.vue')
const Params = () => import(/* webpackChunkName: 'goods' */'../components/Params.vue')
const Categories = () => import(/* webpackChunkName: 'goods' */'../components/Categories.vue')

const Orders = () => import(/* webpackChunkName: 'orders' */'../components/Orders.vue')

const Roles = () => import(/* webpackChunkName: 'rights' */'../components/Roles.vue')
const Rights = () => import(/* webpackChunkName: 'rights' */'../components/Rights.vue')

const Users = () => import(/* webpackChunkName: 'users' */'../components/Users.vue')

const Reports = () => import(/* webpackChunkName: 'reports' */'../components/Reports.vue')

Vue.use(VueRouter)
Vue.prototype.$axios = axios
axios.defaults.baseURL = 'http://localhost:8888/api/private/v1/'
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  // console.log(config)
  config.headers.Authorization = localStorage.getItem('token')
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// Add a response interceptor
axios.interceptors.response.use(function (response) {
  // Do something with response data
  response = response.data
  // console.log(response)
  if (response.meta.status === 401) {
    localStorage.removeItem('token')
    response.meta.msg = '登录状态已失效, 请重新登录'
    router.push('/login')
  }
  return response
}, function (error) {
  // Do something with response error
  return Promise.reject(error)
})
const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/index',
    component: Index,
    children: [
      { path: '', component: Home },
      { path: 'goods', component: Goods, alias: '/goods' },
      { path: 'goods-add', component: GoodsAdd, alias: '/goods-add' },
      { path: 'params', component: Params, alias: '/params' },
      { path: 'categories', component: Categories, alias: '/categories' },
      { path: 'orders', component: Orders, alias: '/orders' },
      { path: 'roles', component: Roles, alias: '/roles' },
      { path: 'rights', component: Rights, alias: '/rights' },
      { path: 'users', component: Users, alias: '/users' },
      { path: 'reports', component: Reports, alias: '/reports' }
    ]
  }

]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  // console.log(to.path) 请求的路由路径
  // 如果是去登陆, 直接放行
  // 如果不是去登陆, 去其他组件, 判断下是否有 token, 有才放行
  const token = localStorage.getItem('token')
  if (to.path === '/login' || token) {
    next()
  } else {
    next('/login')
  }
})
export default router
